<template>
  <el-dialog
    :close-on-click-modal="false"
    title="总承包合同"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="6">
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="form.contractNumber" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="form.contractName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同主体" prop="contractBody">
            <el-input v-model="form.contractBody" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同工期" prop="contractPeriod">
            <el-input v-model="form.contractPeriod" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="基本合同金额" prop="basicAmount">
            <el-input v-model="form.basicAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="有效合同金额" prop="validAmount">
            <el-input v-model="form.validAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="签订时间" prop="signTime">
            <el-date-picker v-model="form.signTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="省份" prop="provinceName">
            <el-select v-model="form.provinceName" :disabled="disableForm" style="width: 100%;" placeholder="请选择省份" @change="provinceChange">
              <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- {{ form.city }}
        <el-col :span="6">
          <el-form-item label="城市" prop="city">
            <el-select v-model="form.city" :disabled="disableForm" style="width: 100%;" placeholder="请选择城市">
              <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="6">
          <el-form-item label="承建模式" prop="constructionMode">
            <el-select v-model="form.constructionMode" :disabled="disableForm" style="width: 100%;" placeholder="请选择承建模式">
              <el-option v-for="item in generalContractInfoConstructionMode" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- {{ form.investmentBody }} -->
        <el-col :span="6">
          <el-form-item label="投资主体" prop="investmentBody">
            <el-select v-model="form.investmentBody" :disabled="disableForm" style="width: 100%;" placeholder="请选择投资主体">
              <el-option v-for="item in generalContractInfoInvestmentBody" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" prop="projectInfoName">
            <!-- <el-select v-model="form.projectType" :disabled="disableForm" style="width: 100%;" placeholder="请选择项目类型">
              <el-option v-for="item in generalContractInfoProjectType" :key="item.name" :label="item.name" :value="item.value" />
            </el-select> -->
            <el-input v-model="form.projectInfoName" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showListModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目类型" prop="projectType">
            <el-select v-model="form.projectType" :disabled="disableForm" style="width: 100%;" placeholder="请选择项目类型">
              <el-option v-for="item in generalContractInfoProjectType" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="详细描述" prop="description">
            <el-input v-model="form.description" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同摘要" prop="summary">
            <el-input v-model="form.summary" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="待建业主" prop="builtOwner">
            <el-input v-model="form.builtOwner" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="甲方名称" prop="employerName">
            <el-input v-model="form.employerName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="com-form-title">扩展信息1</div>
      <el-row>
        <el-col :span="6">
          <el-form-item label="甲方联系人" prop="employerContactPerson">
            <el-input v-model="form.employerContactPerson" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="甲方联系电话" prop="employerContactPhone">
            <el-input v-model="form.employerContactPhone" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="甲方法人" prop="employerLegalPerson">
            <el-input v-model="form.employerLegalPerson" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="乙方名称" prop="employeeName">
            <el-input v-model="form.employeeName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="乙方联系人" prop="employeeContactPerson">
            <el-input v-model="form.employeeContactPerson" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="乙方联系电话" prop="employeeContactPhone">
            <el-input v-model="form.employeeContactPhone" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="乙方法人" prop="employeeLegalPerson">
            <el-input v-model="form.employeeLegalPerson" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开工时间" prop="startTime">
            <el-date-picker v-model="form.startTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="完工时间" prop="finishTime">
            <el-date-picker v-model="form.finishTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="价格调整" prop="priceAdjustment">
            <el-select v-model="form.priceAdjustment" :disabled="disableForm" style="width: 100%;" placeholder="请选择价格调整">
              <el-option v-for="item in generalContractInfoPriceAdjustment" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开工预付款" prop="startPrepayments">
            <el-select v-model="form.startPrepayments" :disabled="disableForm" style="width: 100%;" placeholder="请选择开工预付款">
              <el-option v-for="item in generalContractInfoStartPrepayments" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="甲控材" prop="employerCtrlMaterial">
            <el-select v-model="form.employerCtrlMaterial" :disabled="disableForm" style="width: 100%;" placeholder="请选择甲控材">
              <el-option v-for="item in generalContractInfoEmployerCtrlMaterial" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="甲供材" prop="employerSupplyMaterial">
            <el-select v-model="form.employerSupplyMaterial" :disabled="disableForm" style="width: 100%;" placeholder="请选择甲供材">
              <el-option v-for="item in generalContractInfoEmployerSupplyMaterial" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预付款金额" prop="prepaymentsAmount">
            <el-input v-model="form.prepaymentsAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="质保期信息" prop="warrantyInfo">
            <el-input v-model="form.warrantyInfo" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="质保金比例" prop="warrantyRatio">
            <el-input v-model="form.warrantyRatio" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="com-form-title">扩展信息2</div>
      <el-row>
        <el-col :span="6">
          <el-form-item label="项目信息地址" prop="projectInfoAddress">
            <el-input v-model="form.projectInfoAddress" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="暂列金" prop="temporaryDeposit">
            <el-input v-model="form.temporaryDeposit" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设计费" prop="designFee">
            <el-input v-model="form.designFee" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="设备购置费" prop="devicepurchasefee">
            <el-input v-model="form.devicePurchaseFee" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="建安费" prop="constructionFee">
            <el-input v-model="form.constructionFee" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="暂估价" prop="estimatedFee">
            <el-input v-model="form.estimatedFee" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="其他费" prop="otherFee">
            <el-input v-model="form.otherFee" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="btns" style="padding-bottom: 10px;">
        <el-button type="primary" @click="addRow">新增行</el-button>
        <el-button type="primary" @click="delDetailDataItem">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        :no-page="true"
        :columns="columns"
        highlight-current-row
        :data="detailDataList"
      >
        <template v-slot:settlementNode="{row}">
          <el-input v-model="row.settlementNode" />
        </template>
        <template v-slot:payNode="{row}">
          <el-input v-model="row.payNode" />
        </template>
        <template v-slot:payPercent="{row}">
          <el-input v-model="row.payPercent" />
        </template>
        <template v-slot:payToPricePercent="{row}">
          <el-input v-model="row.payToPricePercent" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" />
        </template>
      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <listSelect :show-modal.sync="showListModal" title="项目名称选择" :columns="listColumns" :api="getProjectInfoList" @getSelectedData="getSelectedRows" />
  </el-dialog>
</template>

<script>
import { addGeneralContractInfo, updateGeneralContractInfo, getGeneralContractInfoDetail, getProjectInfoList } from '@/api/contractManage'
import { getAreaList } from '@/api/common'
import { generalContractInfoInternation, generalContractInfoConstructionMode, generalContractInfoInvestmentBody, generalContractInfoProjectType, generalContractInfoPriceAdjustment, generalContractInfoStartPrepayments, generalContractInfoEmployerCtrlMaterial, generalContractInfoEmployerSupplyMaterial } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import listSelect from '@/components/ListSelect'

export default {
  name: 'AddGeneralContractInfo',
  components: {
    fileUploader,
    listSelect
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getProjectInfoList,
      showListModal: false,
      showFileModal: false,
      targetList: [],
      generalContractInfoInternation,
      generalContractInfoConstructionMode,
      generalContractInfoInvestmentBody,
      generalContractInfoProjectType,
      generalContractInfoPriceAdjustment,
      generalContractInfoStartPrepayments,
      generalContractInfoEmployerCtrlMaterial,
      generalContractInfoEmployerSupplyMaterial,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        contractNumber: '',
        contractName: '',
        contractBody: '',
        contractPeriod: '',
        basicAmount: '',
        validAmount: '',
        signTime: '',
        internation: '',
        provinceCode: '',
        provinceName: '',
        nation: '',
        constructionMode: '',
        investmentBody: '',
        projectType: '',
        builtOwner: '',
        employerName: '',
        employerContactPerson: '',
        employerContactPhone: '',
        employerLegalPerson: '',
        employeeName: '',
        employeeContactPerson: '',
        employeeContactPhone: '',
        employeeLegalPerson: '',
        startTime: '',
        finishTime: '',
        priceAdjustment: '',
        startPrepayments: '',
        employerCtrlMaterial: '',
        employerSupplyMaterial: '',
        prepaymentsAmount: '',
        warrantyInfo: '',
        warrantyRatio: '',
        description: '',
        summary: '',
        projectInfoId: '',
        projectInfoName: '',
        projectInfoAddress: '',
        projectInfoSummary: '',
        remark: '',
        temporaryDeposit: '',
        devicepurchaseFee: '',
        constructionFee: '',
        estimatedFee: '',
        otherFee: '',
        designFee: ''
      },
      showAddDetailModal: false,
      selectRow: null,
      detailDataList: [],
      detailDataItem: {
      },
      listColumns: [
        {
          label: '项目名称',
          prop: 'projName'
        },
        {
          label: '机构',
          prop: 'organization'
        },
        {
          label: '编制人',
          prop: 'founderName'
        },
        {
          label: '编制时间',
          prop: 'createTime',
          slot: 'createTime',
          width: '90'
        },
        {
          label: '承建单位',
          prop: 'contractor'
        },
        {
          label: '省份编码',
          prop: 'provinceCode'
        },
        {
          label: '省名称',
          prop: 'provinceName'
        },
        {
          label: '地市编码',
          prop: 'cityCode'
        },
        {
          label: '市名称',
          prop: 'cityName'
        },
        {
          label: '项目状态',
          prop: 'projStatus',
          slot: 'projStatus'
        },
        {
          label: '项目等级',
          prop: 'projLevel'
        },
        {
          label: '项目类型',
          prop: 'projType',
          slot: 'projType'
        }
      ],
      columns: [
        {
          label: '结算节点',
          slot: 'settlementNode'
        },
        {
          label: '支付节点',
          slot: 'payNode'
        },
        {
          label: '支付比例',
          slot: 'payPercent'
        },
        {
          label: '付至价款比例',
          slot: 'payToPricePercent'
        },
        {
          label: '备注',
          slot: 'remark'
        }
      ],
      showTargetSetListModal: false,
      fileList: [
      ],
      rules: {
        contractName: [
          { required: true, message: '请输入合同名称', trigger: 'change' }
        ],
        projectInfoName: [
          { required: true, message: '请选择项目名称', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开工时间', trigger: 'change' }
        ],
        projectType: [
          { required: true, message: '请选择项目类型', trigger: 'change' }
        ],
        employerName: [
          { required: true, message: '请输入甲方名称', trigger: 'change' }
        ],
        employeeName: [
          { required: true, message: '请输入乙方名称', trigger: 'change' }
        ],
        signTime: [
          { required: true, message: '请选择签订时间', trigger: 'change' }
        ],
        contractPeriod: [
          { required: true, message: '请输入合同工期', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach(key => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.detailDataList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    addRow() {
      this.detailDataList = [
        ...this.detailDataList,
        {
          settlementNode: '',
          payNode: '',
          payPercent: '',
          payToPricePercent: '',
          remark: ''
        }
      ]
    },
    getSelectedRows(data) {
      if (data) {
        // this.supplierInfo = data
        const { projName, id } = data
        this.form.projectInfoName = projName
        this.form.projectInfoId = id
      }
    },
    addDetail() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.detailDataItem))
          this.detailDataList.push(item)
          this.showAddDetailModal = false
          this.$refs.detailForm.resetFields()
        }
      })
    },
    cancelAddDetail() {
      this.showAddDetailModal = false
    },
    delDetailDataItem() {
      if (this.selectRow) {
        const index = this.detailDataList.indexOf(this.selectRow)
        this.detailDataList.splice(index, 1)
      }
    },
    provinceChange(e) {
      // const selectedData = this.provinceData.filter(val => val.name === e)[0]
      // if (selectedData) {
      //   this.form.city = ''
      //   const params = {
      //     parentCode: selectedData.code,
      //     areaType: 2
      //   }
      //   getAreaList(params).then(res => {
      //     this.cityData = res.data || []
      //   })
      // }
    },
    getDocDetail(id) {
      getGeneralContractInfoDetail({ generalContractInfoId: id }).then(res => {
        const { lstAttachment, lstGeneralContractPromise } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstGeneralContractPromise && lstGeneralContractPromise.length > 0) {
          this.detailDataList = lstGeneralContractPromise
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const { provinceName } = this.form
          if (provinceName) {
            this.form.provinceCode = this.provinceData.filter(item => item.name === provinceName)[0].code
          }
          const params = {
            generalContractInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstGeneralContractPromise: this.detailDataList.map(item => {
              return {
                ...item,
                ...this.optType === 'edit' ? {
                  generalContractInfoId: this.data.id
                } : {}
              }
            }),
            lstAttachment: this.fileList
          }
          const fn = this.optType === 'add' ? addGeneralContractInfo : updateGeneralContractInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
